import GlobalD3Environment from "src/_T/D3/scene/GlobalD3Environment";
import { CameraUtils } from "src/_T/Utils/CameraUtils";

//摄像机控制脚本
export default class CameraControl {

    //公开的方法
    public static get Instance(): CameraControl {
        if (!this._Instance) {
            this._Instance = new CameraControl();
        }
        return this._Instance;
    }
    IsStopCameraUpdate: boolean = false;

    public Init() {
        this.m_Camera = GlobalD3Environment.Camera;
        this.Onclick = new Array<Function>();
        this.ray = new Laya.Ray(new Laya.Vector3(), new Laya.Vector3());
        this.hitResult = new Laya.HitResult();
        //获取物理模拟
        this.physicsSimulation = GlobalD3Environment.Scene3D.physicsSimulation;
        this.IsStopCameraUpdate = false;
    }
    SetCameraUpdate(IsUpdate: boolean) {
        this.IsStopCameraUpdate = IsUpdate;
    }
    /**设置摄像机跟随目标 */
    public SetTarget(_Target: Laya.Sprite3D) {
        this.Target = _Target;
    }
    /**更新摄像机 */
    UpdateCamera() {
        if (this.IsStopCameraUpdate) return;
        if (this.Target && !this.Target.destroyed) {
            let Pos = new Laya.Vector3(this.Target.transform.position.x, 119.4, this.Target.transform.position.z - 46.9);
            this.m_Camera.transform.position = Pos;
        }
    }
    /**获取射线检测的资源 */
    public GetCameraRayToHitResult(): Laya.HitResult {
        this.m_Camera.viewportPointToRay(new Laya.Vector2(Laya.stage.mouseX, Laya.stage.mouseY), this.ray);
        if (this.physicsSimulation != null && this.physicsSimulation.rayCast(this.ray, this.hitResult) && this.Onclick != null) {
            return this.hitResult;
        }
        return null;
    }
    /**获取射线检测到的物体 */
    public GetCameraRayToObject(): Laya.Sprite3D {
        this.m_Camera.viewportPointToRay(new Laya.Vector2(Laya.stage.mouseX, Laya.stage.mouseY), this.ray);
        if (this.physicsSimulation != null && this.physicsSimulation.rayCast(this.ray, this.hitResult) && this.Onclick != null) {
            return this.hitResult.collider.owner as Laya.Sprite3D;
        }
        return null;
    }
    //获取屏幕坐标到世界坐标
    public GetViewToWorldPos(): Laya.Vector3 {
        let Pos = new Laya.Vector2(Laya.stage.mouseX, Laya.stage.mouseY);
        return CameraUtils.ScreenPosToWorldPos(this.m_Camera, Pos, 0);
    }
    private Target: Laya.Sprite3D;
    private Onclick: Array<Function>;
    private ray: Laya.Ray;
    private hitResult: Laya.HitResult;
    private physicsSimulation: Laya.PhysicsSimulation;
    private static _Instance: CameraControl;
    private constructor() { }
    public m_Camera: Laya.Camera;
}
